﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 事前事中分析服务
    /// </summary>
    public class RiskConService
    {
        /// <summary>
        /// 3101 明细审核事前分析
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputriskConService> BeforeAnalyze(FsiRequestHeader<InputRiskConServiceresult> fsiRequest,
            string ControllerName)
        {
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string gend = fsiRequest.Input.data.patient_dtos.gend; //性别
                int age = PublicMethod.CalculateAge(fsiRequest.Input.data.patient_dtos.brdy, DateTime.Now);
                string patn_id = fsiRequest.Input.data.patient_dtos.patn_id; //人员编号
                string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id; //就诊id
                List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List;
                if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")
                {
                    fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.encounter_dtos.order_dtos;
                }
                else
                {
                    fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                }

                Random rnd = new Random();
                string connectionString =
                    $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                foreach (var item in fsi_order_dtos_List)
                {
                    string query = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                    var parameter = new List<MySqlParameter>
                    {
                        new MySqlParameter("@med_list_codg", item.hilist_code)
                    };
                    DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                    if (dt.Rows.Count >= 1)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string rule_name = dt.Rows[i]["rule_name"].ToString();
                            string product_name = dt.Rows[i]["product_name"].ToString();
                            string compliance_condition_text = dt.Rows[i]["compliance_condition_text"].ToString();
                            string compliance_condition_num = dt.Rows[i]["compliance_condition_num"].ToString();

                            List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem =
                                new List<Judge_result_detail_dtosItem>();
                            Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                            {
                                vola_item_type = "1",
                                mdtrt_id = curr_mdtrt_id,
                                jrd_id = Guid.NewGuid().ToString(),
                                patn_id = patn_id,
                                rx_id = item.rx_id,
                                vola_amt = item.sumamt
                            };
                            JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                            if (string.IsNullOrEmpty(rule_name))
                            {
                                DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                {
                                    judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                    rule_id = dt.Rows[i]["rule_id"].ToString(),
                                    vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                    mdtrt_id = curr_mdtrt_id,
                                    vola_amt_stas = "1",
                                    jr_id = Guid.NewGuid().ToString(),
                                    patn_id = patn_id,
                                    vola_amt = 1,
                                    sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                    vola_cont = $"规则名称为空！请联系管理员排查！药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                    vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                };
                                dataList.Add(riskConServiceresultInfo);
                            }

                            switch (rule_name)
                            {
                                case "与限定性别不符":
                                    if (gend != compliance_condition_text)
                                    {
                                        DatariskConServiceresult riskConServiceresultInfoxb =
                                            new DatariskConServiceresult
                                            {
                                                judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                                rule_id = dt.Rows[i]["rule_id"].ToString(),
                                                vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                                rule_name = rule_name,
                                                mdtrt_id = curr_mdtrt_id,
                                                vola_amt_stas = "1",
                                                jr_id = Guid.NewGuid().ToString(),
                                                patn_id = patn_id,
                                                vola_amt = 1,
                                                sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                                vola_cont =
                                                    $"性别不符，当前结算性别【{PublicMethod.GetGendStr(gend)}】，药品限制使用性别【{PublicMethod.GetGendStr(compliance_condition_text)}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                                vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                            };
                                        dataList.Add(riskConServiceresultInfoxb);
                                    }

                                    break;
                                case "参保人年龄超出儿童年龄限制" or "就诊人年龄超出儿童年龄限制":
                                    if (string.IsNullOrEmpty(compliance_condition_num) || age == 0)
                                    {
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = dt.Rows[i]["rule_id"].ToString(),
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = rule_name,
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg =
                                                $"年龄入参异常！当前就诊年龄【{age}】，药品限制年龄【{compliance_condition_num}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }
                                    else
                                    {
                                        if (age > decimal.Parse(compliance_condition_num))
                                        {
                                            DatariskConServiceresult riskConServiceresultInfo =
                                                new DatariskConServiceresult
                                                {
                                                    judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                                    rule_id = dt.Rows[i]["rule_id"].ToString(),
                                                    vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                                    rule_name = rule_name,
                                                    mdtrt_id = curr_mdtrt_id,
                                                    vola_amt_stas = "1",
                                                    jr_id = Guid.NewGuid().ToString(),
                                                    patn_id = patn_id,
                                                    vola_amt = 1,
                                                    sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                                    vola_cont =
                                                        $"年龄不符，当前就诊年龄【{age}】，药品限制年龄【{compliance_condition_num}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                                    vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                                };
                                            dataList.Add(riskConServiceresultInfo);
                                        }
                                    }

                                    break;
                                default:
                                    DatariskConServiceresult riskConServiceresultInfonullnl =
                                        new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = dt.Rows[i]["rule_id"].ToString(),
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = rule_name,
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont =
                                                $"未匹配到代码预设的规则！请联系管理员排查！药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                    dataList.Add(riskConServiceresultInfonullnl);
                                    break;
                            }
                        }
                    }
                }

                var output = new OutputriskConService
                {
                    result = dataList
                };
                return output;
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[RiskConService.BeforeAnalyze]明细审核事前分析异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 3102 明细审核事中分析
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputriskConService> CourseAnalyze(FsiRequestHeader<InputRiskConServiceresult> fsiRequest,
            string ControllerName)
        {
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string gend = fsiRequest.Input.data.patient_dtos.gend; //性别
                int age = PublicMethod.CalculateAge(fsiRequest.Input.data.patient_dtos.brdy, DateTime.Now);
                string patn_id = fsiRequest.Input.data.patient_dtos.patn_id; //人员编号
                string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id; //就诊id
                List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List;
                if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")
                {
                    fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.encounter_dtos.order_dtos;
                }
                else
                {
                    fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                }

                Random rnd = new Random();
                string connectionString =
                    $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                foreach (var item in fsi_order_dtos_List)
                {
                    string query = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                    var parameter = new List<MySqlParameter>
                    {
                        new MySqlParameter("@med_list_codg", item.hilist_code)
                    };
                    DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                    if (dt.Rows.Count >= 1)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string rule_name = dt.Rows[i]["rule_name"].ToString();
                            string product_name = dt.Rows[i]["product_name"].ToString();
                            string compliance_condition_text = dt.Rows[i]["compliance_condition_text"].ToString();
                            string compliance_condition_num = dt.Rows[i]["compliance_condition_num"].ToString();

                            List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem =
                                new List<Judge_result_detail_dtosItem>();
                            Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                            {
                                vola_item_type = "1",
                                mdtrt_id = curr_mdtrt_id,
                                jrd_id = Guid.NewGuid().ToString(),
                                patn_id = patn_id,
                                rx_id = item.rx_id,
                                vola_amt = item.sumamt
                            };
                            JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                            if (string.IsNullOrEmpty(rule_name))
                            {
                                DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                {
                                    judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                    rule_id = dt.Rows[i]["rule_id"].ToString(),
                                    vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                    mdtrt_id = curr_mdtrt_id,
                                    vola_amt_stas = "1",
                                    jr_id = Guid.NewGuid().ToString(),
                                    patn_id = patn_id,
                                    vola_amt = 1,
                                    sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                    vola_cont = $"规则名称为空！请联系管理员排查！药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                    vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                };
                                dataList.Add(riskConServiceresultInfo);
                            }

                            switch (rule_name)
                            {
                                case "与限定性别不符":
                                    if (gend != compliance_condition_text)
                                    {
                                        DatariskConServiceresult riskConServiceresultInfoxb =
                                            new DatariskConServiceresult
                                            {
                                                judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                                rule_id = dt.Rows[i]["rule_id"].ToString(),
                                                vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                                rule_name = rule_name,
                                                mdtrt_id = curr_mdtrt_id,
                                                vola_amt_stas = "1",
                                                jr_id = Guid.NewGuid().ToString(),
                                                patn_id = patn_id,
                                                vola_amt = 1,
                                                sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                                vola_cont =
                                                    $"性别不符，当前结算性别【{PublicMethod.GetGendStr(gend)}】，药品限制使用性别【{PublicMethod.GetGendStr(compliance_condition_text)}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                                vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                            };
                                        dataList.Add(riskConServiceresultInfoxb);
                                    }

                                    break;
                                case "参保人年龄超出儿童年龄限制" or "就诊人年龄超出儿童年龄限制":
                                    if (string.IsNullOrEmpty(compliance_condition_num) || age == 0)
                                    {
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = dt.Rows[i]["rule_id"].ToString(),
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = rule_name,
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg =
                                                $"年龄入参异常！当前就诊年龄【{age}】，药品限制年龄【{compliance_condition_num}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }
                                    else
                                    {
                                        if (age > decimal.Parse(compliance_condition_num))
                                        {
                                            DatariskConServiceresult riskConServiceresultInfo =
                                                new DatariskConServiceresult
                                                {
                                                    judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                                    rule_id = dt.Rows[i]["rule_id"].ToString(),
                                                    vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                                    rule_name = rule_name,
                                                    mdtrt_id = curr_mdtrt_id,
                                                    vola_amt_stas = "1",
                                                    jr_id = Guid.NewGuid().ToString(),
                                                    patn_id = patn_id,
                                                    vola_amt = 1,
                                                    sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                                    vola_cont =
                                                        $"年龄不符，当前就诊年龄【{age}】，药品限制年龄【{compliance_condition_num}】，药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                                    vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                                };
                                            dataList.Add(riskConServiceresultInfo);
                                        }
                                    }

                                    break;
                                default:
                                    DatariskConServiceresult riskConServiceresultInfonullnl =
                                        new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = dt.Rows[i]["rule_id"].ToString(),
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = rule_name,
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont =
                                                $"未匹配到代码预设的规则！请联系管理员排查！药品【{product_name}】说明：{dt.Rows[i]["vola_cont"]}",
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                    dataList.Add(riskConServiceresultInfonullnl);
                                    break;
                            }
                        }
                    }
                }

                var output = new OutputriskConService
                {
                    result = dataList
                };
                return output;
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[RiskConService.CourseAnalyze]明细审核事中分析异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }


        /// <summary>
        /// 3103事前事中服务反馈服务
        /// </summary>
        /// <param name="fsiRequest"></param>
        /// <param name="ControllerName"></param>
        /// <returns></returns>
        public async Task<bool> FeedbackAnalyze(FsiRequestHeader<InputFeedbackAnalyze> fsiRequest, string ControllerName)
        {
            try
            {
                //暂时不处理任何逻辑
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[RiskConService.FeedbackAnalyze]事前事中服务反馈异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
    }
}